package admin

import (
	"duoke/context"
	"duoke/model"
	"duoke/service"
	"duoke/tables"
	"duoke/utils/gconv"
	"duoke/utils/orm"
	"duoke/utils/response"
	"github.com/gin-gonic/gin"
)

var Staff = new(staffCtl)

type staffCtl struct{}

func (ctl *staffCtl) List(c *gin.Context) {
	accountR, _ := service.Request.Account(c)
	var req model.ReqList
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	// 分页
	list := make([]model.StaffList, 0)
	query := orm.Db.Where("is_staff =?", 1).Desc("id")
	//判断子账户
	if accountR.Role == "goods" {
		query = query.Where("goods_id IN(" + accountR.GoodsIds + ")")
	} else {
		query = query.Where("acid =?", accountR.Id)
	}
	if req.Keyword != "" {
		query = query.Where("(nickname like%?% OR name like%?% OR phone like%?% OR user_id =?)", req.Keyword, req.Keyword, req.Keyword, req.Keyword)
	}
	if req.GoodsId != "" {
		query = query.Where("goods_id =?", req.GoodsId)
	}
	err := query.Find(&list)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	for i, v := range list {
		orderList := make([]tables.Order, 0)
		orm.Db.Desc("id").Where("(staff_id =? OR from_id =?) AND goods_id =? AND pay_state =?", v.UserId, v.UserId, req.GoodsId, 1).Find(&orderList)
		list[i].OrderNum = len(orderList)
		list[i].OrderList = orderList
		list[i].ShareQrcodeUrl = context.Global.Domain + "/mp/qrcode/?acid=" + gconv.String(v.Acid) + "&type=share&goodsId=" + gconv.String(v.GoodsId) + "&fromId=" + gconv.String(v.UserId)
	}
	response.Success(c, "", list)
}
